import * as xlsx from 'xlsx'
import { ref } from 'vue'
export const exportFn2 = () => {
  let freeCarList = JSON.parse(localStorage.getItem('freeCarList'))
  if (!freeCarList) {
    freeCarList = []
  }
  // 创建字段名映射对象
  const headerMapping = [
    '序号',
    '车牌',
    '施工单位',
    '免费开始时间',
    '免费结束时间',
    '免费区间',
    '车辆类型',
    '车辆年检有效期',
    '车辆保险有效期',
    '更新日期',
    '备注'
  ]

  const wb = xlsx.utils.book_new()
  const ws = xlsx.utils.json_to_sheet(freeCarList)
  xlsx.utils.book_append_sheet(wb, ws, 'Sheet1')
  xlsx.utils.sheet_add_aoa(ws, [headerMapping], { origin: 'A1' })
  //未处理英文表头 (item 的 key)
  xlsx.writeFile(wb, '免费车.xlsx')
}
export const importTable = () => {
  const input = document.createElement('input')
  const tableDataFFF = ref([])
  input.type = 'file'
  input.accept = '.xlsx, .xls'
  input.onchange = e => {
    const file = e.target.files[0]
    const reader = new FileReader()
    reader.onload = e => {
      const data = e.target.result
      const workbook = xlsx.read(data, { type: 'binary' })
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      const tableDataDDD = xlsx.utils.sheet_to_json(worksheet, {
        header: 1
      })
      const headMap = [
        'id',
        'licensePlate',
        'constructionUnit',
        'freeTimeStart',
        'freeTimeEnd',
        'freeSection',
        'vehicleType',
        'theValidityPeriodOfTheAnnualInspectionOfTheVehicle',
        'validityPeriodOfVehicleInsurance',
        'updatedDate',
        'remark'
      ]
      const tableHead = tableDataDDD.shift()
      console.log(tableDataDDD)
      tableDataFFF.value = tableDataDDD.map((value, index, array) => {
        console.log(index)
        console.log('index')
        console.log(value)
        // 创建一个新对象，其中键来自 headMap，值来自当前 value 数组的元素
        const find = {}
        headMap.forEach((key, i) => {
          find[key] = value[i]
        })
        return find
      })
      localStorage.setItem('freeCarList', JSON.stringify(tableDataFFF.value))
      //   search()
      localStorage.setItem('freeCarList-excel-head', JSON.stringify(tableHead))
    }
    reader.readAsArrayBuffer(file)
  }
  input.click()
}
